﻿/******************************************************/
// PostInfoPage プレゼンテーションクラス  
/******************************************************/

using System;
using System.Data;
using System.Globalization;
using System.Resources;
using System.Threading;
using System.Web.UI;
using MAA.Business;
using MAA.Entity;
using System.Web.UI.WebControls;

namespace MAA.Presentation.PRL.Trading
{
    public partial class PostInfoPage : System.Web.UI.Page
    {
        private ResourceManager rm = new ResourceManager("MAA.Presentation.language", System.Reflection.Assembly.GetExecutingAssembly());
        private CultureInfo m_JapanCulture = new CultureInfo("ja-JP");
        private CultureInfo m_VietnameCulture = new CultureInfo("vi");

        private void UpdateUI()
        {
            langPostInformation.Text = rm.GetString("langPostInformation");
            langRiceType.Text = rm.GetString("langRiceType");
            langAmount.Text = rm.GetString("langAmountNotKg");
            langPostTradedAmount.Text = rm.GetString("langPostTradedAmount");
            langUnitPrice.Text = rm.GetString("langUnitPrice");
            langPostPerPrice.Text = rm.GetString("langPostPerPrice");
            langAddress.Text = rm.GetString("langAddress");
            langProvince.Text = rm.GetString("langProvince");
            langDateBuy.Text = rm.GetString("langDateBuy");
            langPosterInformation.Text = rm.GetString("langPosterInformation");
            langReportBreach.Text = rm.GetString("langReportBreach");
            langReason.Text = rm.GetString("langReason");
            RequiredFieldValidator4.Text = rm.GetString("langEnterReason");
            btnReportBreach.Text = rm.GetString("langReport");
            btnCancel.Text = rm.GetString("langCancel");
            langOrder.Text = rm.GetString("langOrder");
            langAmountOrder.Text = rm.GetString("langAmount");
            RequiredFieldValidator1.Text = rm.GetString("langEnterAmount");
            RangeValidator4.Text = rm.GetString("langNumLimit");
            langMin.Text = rm.GetString("langMin");
            langPercent.Text = rm.GetString("langPercent");
            langLess.Text = rm.GetString("langLess");
            langUnitPrice1.Text = rm.GetString("langUnitPrice");
            RequiredFieldValidator2.Text = rm.GetString("langEnterPriceBuy");
            RangeValidator1.Text = rm.GetString("langPriceLimit");
            btnOrder.Text = rm.GetString("langOrder");
            langSentEmailToPoster.Text = rm.GetString("langSentEmailToPoster");
            RequiredFieldValidator3.Text = rm.GetString("langEnterContent");
            btnContact.Text = rm.GetString("langSent");
            lbtOrderList2.Text = rm.GetString("langListOrderNow");
            dgvOrderBuyer.Columns[0].HeaderText = rm.GetString("langName");
            dgvOrderBuyer.Columns[1].HeaderText = rm.GetString("langAmount");
            dgvOrderBuyer.Columns[2].HeaderText = rm.GetString("langPrice");
            dgvOrderBuyer.Columns[3].HeaderText = rm.GetString("langProvince");
            dgvOrderBuyer.Columns[4].HeaderText = rm.GetString("langDateBuy");
            dgvOrderBuyer.Columns[6].HeaderText = rm.GetString("langStatus");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["language"] == null)
            {
                Session["language"] = "vi";
            }
            if (Session["language"].Equals("vi"))
            {
                Thread.CurrentThread.CurrentUICulture = m_VietnameCulture;
                UpdateUI();
            }
            if (Session["language"].Equals("jp"))
            {
                Thread.CurrentThread.CurrentUICulture = m_JapanCulture;
                UpdateUI();
            }
            if (IsPostBack) return;
            long userID = 0;
            if (Session["userID"] != null)
            {
                userID = Convert.ToInt64(Session["userID"]);
            }
            long postID = Convert.ToInt64(Request.QueryString["postID"]);

            BOLTrading bolTrading = new BOLTrading();
            BOLAccount bolAccount = new BOLAccount();
            DataTable tblPost = new DataTable();
            DataTable tblBuyerOrder = new DataTable();
            DataTable tblSeller = new DataTable();

            // View detail information of post
            string messagePost = "";
            long sellerID = 0;
            short status = 0;
            double amount = 0;
            double tradedAmount = 0;

            string lang = Session["language"].ToString();
            if (bolTrading.viewPost(lang, postID, out tblPost, out messagePost))
            {
                if (tblPost.Rows.Count > 0)
                {
                    for (int i = 0; i < tblPost.Rows.Count; ++i)
                    {
                        sellerID = Convert.ToInt64(tblPost.Rows[i]["UserID"]);
                        Session["riceID"] = Convert.ToInt32(tblPost.Rows[i]["RiceID"]);
                        lblPostRice.Text = Convert.ToString(tblPost.Rows[i]["TypeName"]);
                        amount = Convert.ToDouble(tblPost.Rows[i]["Amount"]);
                        lblPostAmount.Text = amount.ToString();
                        tradedAmount = Convert.ToDouble(tblPost.Rows[i]["TradedAmount"]);
                        lblPostTradedAmount.Text = tradedAmount.ToString();
                        lblMaxOrderAmount.Text = (amount - tradedAmount).ToString();
                        lblMinOrderAmount.Text = Convert.ToString(tblPost.Rows[i]["MinOrderAmount"]);
                        lblPostPrice.Text = Convert.ToString(tblPost.Rows[i]["Price"]);
                        lblPostPerPrice.Text = Convert.ToString(tblPost.Rows[i]["PercentPrice"]);
                        lblPostAddress.Text = Convert.ToString(tblPost.Rows[i]["Address"]);
                        lblPostProvince.Text = Convert.ToString(tblPost.Rows[i]["Province"]);
                        lblPostCreateDate.Text = Convert.ToString(tblPost.Rows[i]["UpdateTime"]);
                        status = Convert.ToInt16(tblPost.Rows[i]["Status"]);
                    }
                    Session["sellerID"] = sellerID;
                }
            }
            else
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(),
                    "Alert", "<script>alert('" + PRLCommon.ChangeLanguageMessage(messagePost) + "')</script>", false);
            }

            // View buyers & orders list of post
            string messageOrderList = "";
            lblOrderListMess.Text = null;
            if (bolTrading.viewOrderList(lang, postID, out tblBuyerOrder, out messageOrderList))
            {
                if (tblBuyerOrder.Rows.Count > 0)
                {
                }
                else
                {
                    lblOrderListMess.Text = rm.GetString("langMESSAGE_NO_DATA_ORDER_LIST");
                }
            }
            else
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(),
                    "Alert", "<script>alert('" + PRLCommon.ChangeLanguageMessage(messageOrderList) + "')</script>", false);
            }
            dgvOrderBuyer.DataSource = tblBuyerOrder;
            dgvOrderBuyer.DataBind();

            // View information of seller correspond to post
            string messageSeller = "";
            bool reported = true;
            if (bolAccount.viewSellerInfo(userID, sellerID, out tblSeller, out reported, out messageSeller))
            {
                if (tblSeller.Rows.Count > 0)
                {
                    for (int i = 0; i < tblSeller.Rows.Count; ++i)
                    {
                        lblSellerName.Text = Convert.ToString(tblSeller.Rows[i]["Name"]);
                        impSellerPicture.ImageUrl = Convert.ToString(tblSeller.Rows[i]["ProfilePicture"]);
                        lblSellerAddress.Text = Convert.ToString(tblSeller.Rows[i]["Address"]);
                        lblSellerProvince.Text = Convert.ToString(tblSeller.Rows[i]["Province"]);
                    }
                }
            }
            else
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(),
                    "Alert", "<script>alert('" + PRLCommon.ChangeLanguageMessage(messageSeller) + "')</script>", false);
            }

            // Enable/Disable: button Report Breach, textbox Order Amount, textbox Order Price, button Order, 
            // textArea Contact Content, button Send Contact
            if (status != 1)
            {
                tbxOrderAmount.Enabled = false;
                tbxOrderPrice.Enabled = false;
                btnOrder.Enabled = false;
                btnContact.Enabled = false;
            }
            if (reported == true)
            {
                tbxReason.Enabled = false;
                btnReportBreach.Enabled = false;
            }
            if (userID == 0)
            {
                LblMes.Text = rm.GetString("langMesNeedLogIn");

                divReport.Attributes.Add("style", "display:none");
                divOrder.Attributes.Add("style", "display:none");
                divContact.Attributes.Add("style", "display:none");
            }
            if (userID == sellerID)
            {
                LblMes.Text = rm.GetString("langMyPost");

                divReport.Attributes.Add("style", "display:none");
                divOrder.Attributes.Add("style", "display:none");
                divContact.Attributes.Add("style", "display:none");
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnOrder_Click(object sender, EventArgs e)
        {
            BOLTrading bolTrading = new BOLTrading();
            string message = "";

            // Get information of order
            Order order = new Order();
            order.PostID = Convert.ToInt64(Request.QueryString["postID"]);
            order.UserID = Convert.ToInt64(Session["userID"]);
            order.Amount = Convert.ToInt64(tbxOrderAmount.Text.Trim());
            order.Price = Convert.ToInt32(tbxOrderPrice.Text.Trim());

            // Thuc hien create order

            string lang = Session["language"].ToString();
            // If thuc hien success
            if (bolTrading.createOrder(lang, order, out message))
            {
                // Redirect to TransactionPage
                Response.Redirect("~/PRL.Trading/TransactionPage.aspx");
            }
            // If thuc hien fail
            else
            {
                if (message.Equals(Common.MESSAGE_ERROR_POST_NOT_EXIST))
                {
                    // Show pop-up message: message & Redirect to HomePage
                    ClientScript.RegisterStartupScript(this.GetType(), "popup",
                        "<script type='text/javascript'>alert('" + PRLCommon.ChangeLanguageMessage(message) + "');window.location='../HomePage.aspx'</script>");
                }
                else
                {
                    // Show pop-up message: message & Reload page
                    ClientScript.RegisterStartupScript(this.GetType(), "popup",
                        "<script type='text/javascript'>alert('" + PRLCommon.ChangeLanguageMessage(message) + "');window.location='PostInfoPage.aspx?postID=" + order.PostID + "'</script>");
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnReportBreach_Click(object sender, EventArgs e)
        {
            BOLAccount bolAccount = new BOLAccount();
            long userID = Convert.ToInt64(Session["userID"]);
            long violatorID = Convert.ToInt64(Session["sellerID"]);
            string reason = tbxReason.Text;
            string message = "";

            // Thuc hien report breach

            // If thuc hien success
            if (bolAccount.reportBreach(userID, violatorID, reason, out message) == true)
            {
                // Reload page
                Response.Redirect(Request.RawUrl);
            }
            // If thuc hien fail
            else
            {
                // Show pop-up message: message
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(),
                    "Alert", "<script>alert('" + PRLCommon.ChangeLanguageMessage(message) + "')</script>", false);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            tbxReason.Text = "";
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnContact_Click(object sender, EventArgs e)
        {
            BOLTrading bolTrading = new BOLTrading();
            long userID = Convert.ToInt64(Session["userID"]);
            long receiverID = Convert.ToInt64(Session["sellerID"]);
            string content = tbxContactContent.Text;
            string message = "";

            // Thuc hien send contact message
            bolTrading.createContact(userID, receiverID, content, out message);
            tbxContactContent.Text = "";
            ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(),
                "Alert", "<script>alert('" + PRLCommon.ChangeLanguageMessage(message) + "')</script>", false);
        }

        protected void dgvOrderBuyer_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Cells[6].Text = PRLCommon.ChangeLanguageStatus(e.Row.Cells[6].Text);
            }
        }
    }
}